/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package xmppjavaclient;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
import org.jivesoftware.smack.*;
import org.jivesoftware.smack.packet.*;
import java.net.*;
import javax.swing.tree.*;
/**
 *
 * @author Administrator
 */
public class RosterPanel extends JPanel {

	public RosterPanel() {
		this(null);
	}

	public RosterPanel(XMPPJavaClientFrame mfrm) {
		connection = TheGlobal.connection;
		imageOnLine = new ImageIcon(RosterPanel.class.getResource("resources/1.gif"));
		imageOffLine = new ImageIcon(RosterPanel.class.getResource("resources/2.gif"));
		rosterBlocks = new Hashtable<String, JButton>();
		this.setLayout(new GridLayout(0, 1));
		TheGlobal.roster = TheGlobal.connection.getRoster();
		Roster roster = TheGlobal.roster;
		roster.setSubscriptionMode(Roster.SubscriptionMode.valueOf("accept_all"));
		Collection<RosterEntry> entries = roster.getEntries();
		for (RosterEntry entry : entries) {
			Presence presence = roster.getPresence(entry.getUser());
			JButton bt1 = new JButton(entry.getUser(), imageOffLine);
			if( presence!=null && presence.isAvailable() )
			{
				bt1.setIcon(imageOnLine);
			}
			rosterBlocks.put(entry.getUser(), bt1);
			bt1.addActionListener(new ActionListener() {

				public void actionPerformed(ActionEvent e) {
					try {
						JButton btE = (JButton) e.getSource();
						String strTo = btE.getText();
						ChatFrame ml = new ChatFrame();
						Chat chat = connection.getChatManager().createChat(strTo, ml);
						ml.setChat(chat);
						ml.setVisible(true);
					} catch (Exception ex) {
						ex.printStackTrace();
					}
				}
			});
			this.add(bt1);
		}

		roster.addRosterListener(new RosterListener() {

			public void entriesAdded(Collection<String> addresses) {
				System.out.println("entriesAdded");
			}

			public void entriesDeleted(Collection<String> addresses) {
				System.out.println("entriesDeleted");
			}

			public void entriesUpdated(Collection<String> addresses) {
				System.out.println("entriesUpdated");
			}

			public void presenceChanged(Presence presence) {
				System.out.println("presenceChanged");
				String from = presence.getFrom();
				String Jid = from.substring(0, from.indexOf('/'));
				System.out.println(Jid);
				JButton bt = (JButton) rosterBlocks.get(Jid);
				if (presence.isAvailable()) {
					bt.setIcon(imageOnLine);
				} else {
					bt.setIcon(imageOffLine);
				}
				//bt.setVisible(true);
			}
		});
	}
	private XMPPConnection connection;
	private ImageIcon imageOnLine;
	private ImageIcon imageOffLine;
	private Hashtable<String, JButton> rosterBlocks;
}
